import re
from rest_framework import serializers
from rest_framework.exceptions import APIException
from apps.models import User, LoginLog
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth.hashers import make_password, check_password

class UserUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'
        extra_kwargs = {
            'password': {'write_only': True},
            'repassword': {'write_only': True}
        }

class UserSerializer(serializers.ModelSerializer):
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', required=False)
    repassword = serializers.CharField(write_only=True)
    class Meta:
        model = User
        fields = '__all__'

        extra_kwargs = {
                "username": {"max_length": 30, "min_length": 2},
                "password": {"max_length": 20, "min_length": 6},
                "repassword": {"max_length": 20, "min_length": 6}
            }

    print('进来啦！')

    def create(self, validated_data):
        username = validated_data.pop('username')
        password = validated_data.pop('password')
        repassword = validated_data.pop('repassword')
        # assert password == repassword, APIException('两次密码不一致。')
        # repassword = validated_data.pop("repassword")
        assert password == repassword, APIException('两次密码不一致！')
        salt_password = make_password(password)
        if User.objects.filter(username=username):
            raise APIException(f'用户 {username} 已存在！')
        user = User.objects.create(username=username, password=salt_password, role=2, status=0)
        return user


class LoginLogSerializer(serializers.ModelSerializer):
    log_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', required=False)

    class Meta:
        model = LoginLog
        fields = '__all__'

    def create(self, validated_data):

        return LoginLog.objects.create(**validated_data)


class LoginSerializer(serializers.ModelSerializer):
    cover=serializers.CharField(read_only=True)
    class Meta:
        model = User
        fields = '__all__'
        
    def _get_user(self, attrs):
        username = attrs.get('username')
        print(username)
        password = attrs.get('password')
        print('password',password)

        # if re.match(r"^1[3-9]\d{9}$", username):
        #     user = User.objects.filter(mobile=username).first()
        # elif re.match(r".*?@.*[com|cn|net]", username):
        #     user = User.objects.filter(email=username).first()
        # else:1
        user = User.objects.filter(username=username).first()
        print('user',user)
        print('user.password',user.password)

        if user and check_password(password, user.password):
            return {'user': user, "username": username, "user_id": user.id}
        else:
            raise APIException('用户名或密码错误, 请重试~')

    def _get_token(self, user):
        return  RefreshToken.for_user(user)

    def _pre_data(self, username, user_id, token):
        self.context['username'] = username
        self.context['token'] = str(token)
        self.context['user_id'] = user_id

    
    def validate(self, attrs):
        # 获取用户
        user = self._get_user(attrs)['user']
        username = self._get_user(attrs)['username']
        user_id = self._get_user(attrs)['user_id']
        # 获取token
        token = self._get_token(user)
        # 数据拼接
        self._pre_data(username=username, token=token, user_id=user_id)
        
        # 别忘记返回 不然会报错
        return attrs